<?php

include 'logger.php';
include 'settings.php';
include 'db/providerfactory.php';
include 'converter.php';
include '../lib/twitter.php';

class Application
{
	public $config;
	private $convert;
	private $db;

	public function __construct($config, $converter, $dbprov)
	{
		if ($config instanceof Settings)
			$this->config = $config;
		else
			Logger::getInstance()->error("Not valid config value in Application::__construct;");
			
		if ($converter instanceof Converter)
			$this->convert = $converter;
		else
			Logger::getInstance()->error("Not valid converter value in Application::__construct;");
			
		if ($dbprov instanceof iDatabase)
			$this->db = $dbprov;
		else
			Logger::getInstance()->error("Not valid dbprov value in Application::__construct;");
	}
	
	public function addUrl($long)
	{
		if ( substr($long, 0, 7) == "http://" )
		{
			$long = substr($long, 7);
		}
		$existUrl = $this->searchUrl($long);
		if ( !isset($existUrl) ) 
		{
			$short = $this->convert->convert($this->count());
			$query = "INSERT INTO `".$this->config->db_database."`.`urls` (`long`, `short`)
							 VALUES ('{$long}', '{$short}');";
			$this->db->query($query);
			$this->remember($short);
			return $short;
		}
		else
		{
			return $existUrl;
		}
	}
	
	public function searchUrl($url)
	{
		$query = "SELECT `short` FROM `".$this->config->db_database."`.`urls`
				  WHERE `long`='{$url}' LIMIT 1";
		$res = $this->db->query($query);
		return $res[0];
	}
	
	public function searchLongUrl($url)
	{
		$query = "SELECT `long` FROM `".$this->config->db_database."`.`urls`
				  WHERE `short`='{$url}' LIMIT 1";
		$res = $this->db->query($query);
		return $res[0];
	}
	
	public function visit($url)
	{
		$query = "UPDATE `".$this->config->db_database."`.`urls` SET `visited`=
				  `visited`+1 WHERE `long`='{$url}'";
		$this->db->query($query);
	}
	
	public function getVisited($url)
	{
		$query = "SELECT `visited` FROM `".$this->config->db_database."`.`urls`
				  WHERE `short`='{$url}' LIMIT 1";
		$res = $this->db->query($query);
		return $res[0];
	}
	
	public function showShortened()
	{		
		if ( isset($_COOKIE['squeez_count']) )
		{
			echo '<table border=1 bgcolor=#F3E5FF style="border-style: groove; border-width=1px; border-color=grey;">';
			echo '<caption><center><b>URLs shortened by you:</b></center></caption><br>';
			echo '<tr align=center><td style="padding: 2px;">Short</td><td>Long</td><td>Visited</td></tr>';
			for ( $i = $_COOKIE['squeez_count']; $i > 0; $i-- )
			{
				echo "<tr align=center>";
				$url = $_COOKIE['url'];
				$shortUrl = $this->config->domain.$url[$i];
				$shortUrlWithoutHttp = substr($shortUrl, 7);
				$longUrl = $this->searchLongUrl($url[$i]);
				if ( strlen($longUrl) > 50 ) $longUrl = substr($longUrl, 0, 50)."...";
				$visited = $this->getVisited(substr($shortUrlWithoutHttp, 10));

				echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'><a href=$shortUrl>$shortUrlWithoutHttp</a></td>";
				echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'><a href=$shortUrl>$longUrl</a></td>";
				echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'>$visited</td>";
				echo "</tr>";				
			}
			echo '</table>';
		} 
		else
		{
			echo "<b>You've no any shortened urls</b>";
		}
	}
	
	public function top($limit = 5)
	{	
		$query = "SELECT * FROM `".$this->config->db_database."`.`urls` ORDER BY `visited` DESC LIMIT 5";
		return $this->db->query($query);		
	}
	
	public function showTop()
	{
		$urls = $this->top();
		echo '<table border=1 bgcolor=#F3E5FF style="border-style: groove; border-width=1px; border-color=grey;">';
		echo '<caption><center><b>Top visited:</b></center></caption><br>';
		echo '<tr align=center><td style="padding: 2px;">Short</td><td>Long</td><td>Visited</td></tr>';
		foreach ($urls as $url)
		{
			echo "<tr align=center>";
			$shortUrl = $this->config->domain.$url['short'];
			$shortUrlWithoutHttp = substr($shortUrl, 7);
			$longUrl = $url['long'];
			if ( strlen($longUrl) > 50 ) $longUrl = substr($longUrl, 0, 50)."...";
			$visited = $url['visited'];

			echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'><a href=$shortUrl>$shortUrlWithoutHttp</a></td>";
			echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'><a href=$shortUrl>$longUrl</a></td>";
			echo "<td style='border-style:none; padding: 8px 2px 8px 2px;'>$visited</td>";
			echo "</tr>";
		}
		echo '</table>';
	}
	
	public function truncate()
	{
		$query = "TRUNCATE urls";
		$this->db->query($query);		
		$count = $_COOKIE['squeez_count'];
		setcookie("squeez_count", "", time()-3600);
		for ( $i = 1; $i < $count+1; $i++)
		{
			setcookie("url[$i]", "", time()-3600);
		}
	}
	
	public function count()
	{
		$query = "SELECT COUNT(*) FROM `".$this->config->db_database."`.`urls`";
		$res = $this->db->query($query);
		return $res[0];
	}
	
	public function tweet($username, $password, $tweet)
	{				
		$twitter = new twitter($username, $password);
		$twitter->updateStatus($tweet);	
	}
	
	public function showLink($url, $short)
	{
		echo '<br><br>';		
		print "<div>".$url."</div><br>";
		echo "<button id='show'> Tweet </button><br>";					
	}
	
	public function remember($short)
	{
		if ( !isset($_COOKIE['squeez_count']) )
		{
			setcookie("squeez_count", 1);
			setcookie("url[1]", $short);				
		} 
		else
		{
			$count = $_COOKIE['squeez_count'];
			$count++;
			setcookie("squeez_count", $count);
			setcookie("url[{$count}]", $short);
		};
	}
};

$conf = new Settings();
$dbprov = ProviderFactory::create($conf->db_provider,
	$conf->db_host,$conf->db_database,$conf->db_username, $conf->db_password, "cp1251");
$conv = new Converter();

$app = new Application($conf, $conv, $dbprov);

?>